<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <span style="line-height: 32px;">{{data.spckmc}}</span>
      <el-form-item label="仓位" prop="ckcw">
        <el-input v-model="data.ckcw" placeholder="请输入仓位" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="" prop="allyCheck">
        <el-checkbox v-model="data.allyCheck" @keyup.enter.native="handleQuery">显示所有仓位</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <input v-if="isChange" type="file" name="file" ref="uploadFile" style="display: none"
               @change="uploadFileChange"/>
        <el-button size="mini" @click="handleUpdate(null,'仓位导入')"
                   v-hasPermi="['zhcloud:position:import']"
        >仓位导入
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" @click="handleUpdate(null,'导入模板')"
                   v-hasPermi="['zhcloud:position:import']"
        >导入模板
        </el-button>
      </el-form-item>
      <!-- <el-form-item>
        <el-button
          size="mini"
          @click="handleUpdate(null,'删除')"
          v-hasPermi="['zhcloud:position:del']"
        >删除
        </el-button>
      </el-form-item> -->
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleUpdate(null,'添加仓位')"
          v-hasPermi="['zhcloud:position:add']"
        >添加仓位
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleUpdate(null,'批量添加仓位')"
          v-hasPermi="['zhcloud:position:add']"
        >批量添加仓位
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="handleUpdate(null,'导出勾选数据')"
          v-hasPermi="['zhcloud:position:list']"
        >导出勾选数据
        </el-button>
      </el-col>
    </el-row>
    <el-table ref="zdspcwTable" v-loading="loading" :data="list" :height="tableHeight">
      <af-table-column label="" align="center" fixed="left" width="35px" type="selection"></af-table-column>
      <el-table-column label="操作" align="center" fixed="left" width="100px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,'属性')"
            v-hasPermi="['zhcloud:position:modify']"
          >属性
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,'库存')"
            v-hasPermi="['zhcloud:zdspck:stock']"
          >库存
          </el-button>
        </template>
      </el-table-column>
      <af-table-column label="仓位名称" align="center" prop="ckcw"/>
      <af-table-column label="仓位容量(吨)" align="center" prop="cwrl"/>
      <af-table-column label="仓位面积" align="center" prop="mj"/>
      <af-table-column label="已用容量(吨)" align="center" prop="stock"/>
      <af-table-column label="是否停用" align="center" prop="state"/>
      <af-table-column label="仓位备注" align="center" prop="cwbz"/>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-drawer :title="title" :visible.sync="open" size="35%">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="仓库名称" prop="saddress" >
              <span style="line-height: 32px;">{{data.spckmc}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="仓位名称" prop="ckcw" :rules="rules.saddress">
              <el-input v-model="form.ckcw" placeholder="请输入仓位名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="仓位容量(吨)" prop="cwrl" :rules="rules.cwrl">
              <el-input v-model="form.cwrl" placeholder="请输入仓位容量"/>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="仓位面积(平方米)" prop="mj" :rules="rules.mj">
              <el-input v-model="form.mj" placeholder="请输入仓位面积"/>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="是否停用" prop="state">
              <el-checkbox v-model="form.stateCheck">停用</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="仓位备注" prop="cwbz">
              <el-input v-model="form.cwbz" placeholder="请输入仓位备注"/>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="" prop="">
              <el-button v-show="title === '属性'" style="margin-top: 15px" type="primary" @click="submitForm('修改仓位','form')">
                修改仓位
              </el-button>
              <el-button v-show="title === '添加仓位'" style="margin-top: 15px" type="primary" @click="submitForm('添加', 'form')">
                添加
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
    <!-- 批量添加仓位 -->
    <el-dialog :title="batch_title + ' - ' + data.spckmc" :visible.sync="batch_open" width="1024px" append-to-body>
      <el-table :height="clientHeight - 300" style="overflow: auto;" :data="tableData">
        <el-table-column
          v-for="(item, idx) in tableColumn"
          :key="idx"
          :prop="item.prop"
          :label="item.label"
        >
          <template slot-scope="scope">
            <div class=" table-operation">
              <el-input :ref="'el-input-' + idx" v-model="scope.row[item.prop]"/>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :width="50">
          <template slot-scope="scope">
            <div class="table-operation">
              <a class="color-ff9" @click="operateDel(scope.$index)">删除</a>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="operateAdd()" icon="el-icon-plus">增加行</el-button>
        <el-button type="primary" @click="batchSubmitForm">添加仓位</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {list, modifyPosition, addPosition, delPosition, positionImport} from "@/api/zdspcw/api";
  import ExportJsonExcel from 'js-export-excel';

  export default {
    name: "Zdspcw",
    data() {
      return {
        isChange: true,
        tableData: [],
        tableColumn: [
          {
            prop: 'ckcw',
            label: '仓位'
          },
          {
            prop: 'mj',
            label: '仓位面积(平方米)'
          },
          {
            prop: 'cwrl',
            label: '仓位容量(吨)'
          },
          {
            prop: 'cwbz',
            label: '仓位备注'
          }
        ],
        options: [],
        clientHeight: document.documentElement.clientHeight,
        tableHeight: 500,// 定义table高度
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 仓库表格数据
        list: [],
        delList: [],
        exportList: [],
        // 是否显示弹出层
        open: false,
        title: '',
        form: {},
        sForm: {
          ckcw: "",
          cwbz: "",
          cwrl: "",
          liid: "",
          mj: "",
          spckid: "",
          state: ""
        },
        batch_open: false,
        batch_title: '',
        batch_form: [],
        // 页码
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        row: null,
        // 页码
        data: {
          ckcw: '',
          ally2: '',
          allyCheck: false,
          spckmc: '',
          spckid: ''
        },
        rules: {
          ckcw: [
            { required: true, message: "仓位名称不能为空", trigger: "blur" }
          ],
          cwrl: [
            { required: true, message: "仓位容量不能为空", trigger: "blur" }
          ],
          mj: [
            { required: true, message: "仓位面积不能为空", trigger: "blur" }
          ],
        }
      };
    },
    mounted() {
      //  重置浏览器高度
      window.onresize = () => {
        this.clientHeight = document.documentElement.clientHeight;
      }
    },
    created() {
      this.getList();
    },
    watch: {
      '$route': {
        handler: function (to, from) {
          if (to.path === '/storage/storageSetting/zdspcw/index') {
            this.getList()
          }
        },
        deep: true
      }
    },
    methods: {
      operateDel(index) {
        this.$delete(this.tableData, index)
      },
      operateAdd() {
        this.tableData.push({
          ckcw: '',
          mj: '',
          cwrl: '',
          spckid: this.data.spckid
        })
      },
      getList() {
        this.data.spckmc = decodeURIComponent(this.getQueryVariable('spckmc'));
        this.data.spckid = this.getQueryVariable('spckid');
        if (!this.data.spckid) {
          return
        }
        this.loading = true;
        if (this.data.allyCheck) {
          this.data.ally2 = '1'
        } else {
          this.data.ally2 = ''
        }
        list(this.data, this.queryParams).then(response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        //  初始值，自己定义
        this.tableHeight = this.clientHeight - 260
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      batchSubmitForm() {
        this.loading = true;
        addPosition(this.tableData).then(response => {
          if (response.code !== 200) {
            this.$modal.msgError(response.msg);
          } else {
            this.$modal.msgSuccess("保存成功");
            this.getList();
            this.batch_open = false;
          }
        })
        this.loading = false;
      },
      submitForm(type, formName) {
        this.$refs[formName].validate((valid, data) => {
        if(valid) {
          this.form.state = this.form.stateCheck ? '停用' : '';
          if ('修改仓位' === type) {
            const sForm = this.sForm
            for(let i in sForm) {
              sForm[i] = this.form[i]
              sForm[i] = sForm[i] == undefined?'':sForm[i]
            }
            this.$modal.loading("数据正在修改中，请稍等...")
            modifyPosition(this.sForm).then(response => {
              this.$modal.closeLoading()
              if (response.code !== 200) {
                this.$modal.msgError(response.msg);
              } else {
                this.$modal.msgSuccess("保存成功");
                this.getList();
                this.open = false;
              }
            }).catch(()=> {
              this.$modal.closeLoading()
            })
          }
          if ('添加' === type) {
            const sForm = this.sForm
            let param = new Array()
            this.form.spckid = this.data.spckid
            for(let i in sForm) {
              sForm[i] = this.form[i]
              sForm[i] = sForm[i] == undefined?'':sForm[i]
            }
            param.push(this.sForm)
            this.$modal.loading("数据正在添加中，请稍等...")
            addPosition(param).then(response => {
              this.$modal.closeLoading()
              if (response.code !== 200) {
                this.$modal.msgError(response.msg);
              } else {
                this.$modal.msgSuccess("保存成功");
                this.getList();
                this.open = false;
              }
            }).catch(()=> {
              this.$modal.closeLoading()
            })
          }
        } else {
            for(let i in data) {
              const item = data[i]
              for(let j in item) {
                const message = item[j].message
                return this.$modal.msgError(message)
              }
            }
            return false
          }
        })
      },
      handleUpdate(row, title) {
        if ('导出勾选数据' === title) {
          this.loading = true;
          this.$refs.zdspcwTable.selection.forEach(e => this.exportList.push(e))
          if (this.exportList.length > 0) {
            let option = {}
            option.fileName = '仓位数据'
            option.datas = [
              {
                sheetData: this.exportList,//数据
                sheetName: 'sheet',
                //表头数据对应的sheetData数据
                sheetFilter: ['ckcw', 'cwrl', 'mj', 'stock', 'state', 'cwbz'],
                sheetHeader: [
                  //表头数据
                  '仓位名称', '仓位容量(吨)', '仓位面积', '已用容量(吨)', '是否停用', '仓位备注'],
              }
            ]
            let excel = ExportJsonExcel(option)
            excel.saveExcel()
          } else {
            this.$modal.msgError('请勾选数据');
          }
          this.loading = false;
        }
        if ('属性' === title) {
          row.stateCheck = false
          this.form = Object.assign({}, row);
          this.form.stateCheck = this.form.state && this.form.state !== '' ? true : false
          this.open = true;
          this.title = title;
        }
        if ('添加仓位' === title) {
          this.form = Object.assign({}, {stateCheck: false});
          this.open = true;
          this.title = title;
        }
        if ('批量添加仓位' === title) {
          this.tableData.push({
            ckcw: '',
            mj: '',
            cwrl: '',
            spckid: this.data.spckid
          });
          this.batch_open = true;
          this.batch_title = title;
        }
        if ('删除' === title) {
          this.loading = true;
          this.$refs.zdspcwTable.selection.forEach(e => this.delList.push(e.liid))
          if (this.delList.length > 0) {
            delPosition(this.delList).then(response => {
              if (response.code !== 200) {
                this.$modal.msgError(response.msg);
              } else {
                this.$modal.msgSuccess("保存成功");
                this.getList();
                this.open = false;
              }
            })
          } else {
            this.$modal.msgError('请勾选数据');
          }
          this.loading = false;
        }
        if ('导入模板' === title) {
          this.download('/storage/category/importTemplate', {
            ...this.queryParams
          }, `excel-${new Date().getTime()}.xlsx`)
        }
        if ('仓位导入' === title) {
          this.$refs.uploadFile.click();
          this.isChange = false // 销毁
        }
        if ('库存' === title) {
          this.$router.push("/storage/storageSetting/zdspck/stock?spckmc=" + this.data.spckmc + "&spckid=" + this.data.spckid + "&ckcw=" + row.ckcw + "&liid=" + row.liid);
        }
      },
      uploadFileChange(file) {
        this.loading = true;
        let files = file.target.files[0];
        if (!files) {
          return false;
        } else if (!/\.(xlsx)$/.test(files.name.toLowerCase())) {
          this.$modal.msgError('上传格式不正确，请上传xlsx格式');
          return false;
        }
        const formData = new FormData();
        formData.append("file", files);
        formData.append("spckid", this.data.spckid);
        positionImport(formData).then(response => {
          if (response.code !== 200) {
            this.$modal.msgError(response.msg);
          } else {
            this.$modal.msgSuccess("保存成功");
            this.getList();
            this.open = false;
          }
        })
        this.isChange = true// 重建
        this.loading = false;
      }
    }
  };
</script>
